/* 获取购物车数据 */
import cd from '/api/cartData.js';
(() => {
    $('.header-top-nav-wrap').load('/components/head-nav.html');
    $('.head').load('/components/head-search.html', () => {
        $('.mycart').hide();
        $('.logo_dropdown').hide();
        $('.search-bar').css('border-color', "#E12118").find('.search-btn').css('background-color', "#E12118");
        $('.search-btn').on('click', function() {
            const key = $('.search-key').val();

            // console.log(key ? "q=" + key : "title=" + $('.search-key').attr('placeholder'));
            location.href = '/pages/list.html?' + (key ? "q=" + key : "title=" + $('.search-key').attr('placeholder'));
        })
    });
    generateCartList();
    $('.bottom-footer-wrap').load('/components/bottom-footer.html');

    function generateCartList() {
        cd.getCart(data => {
            if (data == 'err') {
                $('.noLogin').show();
                return
            } else if (data == 'noData') {
                $('.noData').show();
                return
            }
            let totalPrice = 0;
            let str = '';
            $('.num').text(data.length);
            data.forEach(el => {
                const [count, p] = el;

                totalPrice += p.price * count;
                str += `
                <ul class="items cart-nav w" data-id="${p.pid}" >
                    <li>
                        <input type="checkbox" class="check" data-id="${p.pid}">
                    </li>
                    <li>
                        <a href="../pages/detial.html?pid=${p.pid}">
                            <img src="${p.imgsrc}" alt="">
                            <p>${p.name}</p>
                        </a>
                    </li>
                    <li><a href="../pages/list.html?shop=${p.shop}">${p.shop}</a></li>
                    <li>￥<em  class='price'>${p.price}</em></li>
                    <li>
                        <div class="cart-num">
                            <button class="btn_del">
                                <i class="del" data-id="${p.pid}"></i>
                            </button>
                            <div>
                                <input class="numInput" data-id="${p.pid}" type="text" min="1" max="200" value="${count}" data-id="${p.pid}">
                            </div>
                            <button class="btn_add">
                                <i class="add"  data-id="${p.pid}"></i>
                            </button>
                        </div>
                        <p class="ac" ${p.count==0?"style='display:block'":""}>无货</p>
                    </li>
                    <li>
                        ￥<strong>${parseInt(p.price * count*100)/100}</strong>
                    </li>
                    <li>
                        <p class="ac pdel" data-id="${p.pid}">删除</p>
                    </li>
                </ul>
                `;

            })
            $('.cart-list').html(str);
            init();
        })
    }

    function init() {
        /* 全删 */
        $('.items .pdel').on('click', function() {
            // console.log($(this).data('id'));
            const pid = $(this).data('id');
            cd.del(pid, () => {
                $(this).parentsUntil('div', 'ul').remove();
                // generateCartList();
                $('.checkAll').prop('checked', $('.check:checked').length == $('.check').length)
                $('.num').text($('.items').length);
                setTotalPrice();
            });
        })
        /* 增加和删除 */
        $('.cart-num').on('click', function(e) {
            const [c, pid] = [e.target.className, $(e.target).data('id')]
            if (c == "del") {
                cd.reduce(pid, (data, counts) => {
                    $(`.numInput[data-id="${pid}"]`).val(counts);
                    // generateCartList();
                    setPrice();
                })

            } else if (c == "add") {
                // console.log(n);
                cd.add(pid, (data, counts) => {
                    $(`.numInput[data-id="${pid}"]`).val(counts);
                    // generateCartList();
                    setPrice();
                });
            }


        })
        /* 输入添加商品数量 */
        $('.numInput').on('blur', function() {
            // console.log($(this).data('id'), $(this).val());
            cd.update($(this).data('id'), Math.abs($(this).val()), () => {
                // generateCartList();
                setPrice()
            }, true);
        })
        /* 全选 */
        $('.checkAll').on('click', function() {
            $('.check').prop('checked', $(this).prop('checked'));
            $('.checkAll').prop('checked', $(this).prop('checked'));
            setTotalPrice();
        })
        /* 单选 */
        $('.check').on('click', function() {
            $('.checkAll').prop('checked', $('.check:checked').length == $('.check').length)
            setTotalPrice()
        })
        /* 删除选中 */
        $('.delChecked').on('click', function() {
            let arr = [];
            $('.check:checked').each((index, el) => {
                arr.push($(el).data('id'));
            });
            cd.del(arr, (count, p) => {
                $('.num').text(0);
                $('.cart-list').html('');
                $('.checkAll').prop('checked', false);
                generateCartList();
            })

        })
        /* 结算 */
        $('.settled').on('click', function() {
            let d = {};
            $('.check:checked').each((index, el) => {
                d[$(el).data('id')] = $(el).parent().parent().find('.numInput').val();
            })
            // console.log(d);
            localStorage.setItem('checkoutData', JSON.stringify(d));
            location.href = `/pages/checkout.html`;
        })
    }
    /* 更改数量 */
    function setPrice() {
        $('.items strong').each((index, el) => {
            // console.log($(el).parent().parent().find('.price'));
            // console.log($(el).parent().parent().find('.numInput'));
            const price = parseInt(Math.abs($(el).parent().parent().find('.price').text()) * Math.abs($(el).parent().parent().find('.numInput').val()) * 100) / 100;
            $(el).text(price);
        })
        setTotalPrice();
    }
    /* 设置总价 */
    function setTotalPrice() {
        let totalPrice = 0;
        // console.log($('.check'));
        $('.check:checked').each((index, el) => {
            // console.log(Number($(el).parent().siblings().find('strong').text()));
            totalPrice += Number($(el).parent().siblings().find('strong').text());
            // }
        })
        $('.checkedNum').text($('.check:checked').length);
        // console.log(totalPrice);
        $('.totalPrice').text(parseInt(totalPrice * 100) / 100);
    }
})()


/*
<ul class="items cart-nav w">
    <li>
        <input type="checkbox" class="check">
    </li>
    <li>
        <a href="">
            <img src="https://img14.360buyimg.com/n7/jfs/t1/138006/39/20979/98747/619c531aEb08f1955/5473fcc418db0bd8.jpg"
                alt="">
            <p>乐之 浓郁芝士夹心饼干 咸味早餐网红办公室零食 218g（270/360天 两个保质期随机发货</p>
        </a>
    </li>
    <li>亿滋京东自营官方旗舰店</li>
    <li>16.90</li>
    <li>
        <div class="cart-num">
            <button class="btn_del">
                <i></i>
            </button>
            <div>
                <input class="num" type="text" min="1" max="200" value="1">
            </div>
            <button class="btn_add">
                <i></i>
            </button>
        </div>
        <p class="ac">无货</p>
    </li>
    <li>
        <strong>185</strong>
    </li>
    <li>
        <p class="ac">删除</p>
    </li>
</ul>
*/